import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  partListApi,
  partStoreApi,
  partUpdateApi,
  partDeleteApi,
  partShowApi,
  supplierSelectApi,
  categorySelectApi
} from "@/api/quotedPriceApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    keyword: "",
    type: "",
    dateRange: [],

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const categoryOption = ref([
    {id: 1, name: '设备'},
    {id: 2, name: '配件'},
    {id: 3, name: '产品'},
  ])
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      width: 60
    },
    {
      label: "配件名称",
      prop: "partName",
      formatter:(row: any)=> {
        return row.partName ?? '--';
      }
    },
    {
      label: "配件规格",
      prop: "norm",
      formatter:(row: any)=> {
        return row.norm ?? '--';
      }
    },
    {
      label: "配件分类",
      prop: "category.name",
      formatter:(row: any)=> {
        return row.category?.name ?? '--';
      }
    },
    {
      label: "品牌",
      prop: "brand.brandName",
      formatter:(row: any)=> {
        return row.brand?.brandName ?? '--';
      }
    },
    {
      label: "价格(元)",
      prop: "price",
      formatter:(row: any)=> {
        return row.price ?? '--';
      }
    },
    {
      label: "内部型号",
      prop: "code",
      formatter:(row: any)=> {
        return row.code ?? '--';
      }
    },
    {
      label: "供应商",
      prop: "supplier.supplierName",
      formatter:(row: any)=> {
        return row.supplier?.supplierName ?? '--';
      }
    },

    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 140
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const res: any = await partListApi(toRaw(form));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.keyword = "";
    form.type = "";
    form.dateRange = [];
    formEl.resetFields();
    onSearch();
  };

  async function openDialog(title = "创建配件", row?: FormItemProps) {
    const resSupplier: any = await supplierSelectApi()
    const resCategory: any = await categorySelectApi({type: 2})
    let formInline = {
      title: title,
      id: row?.id ?? "",
      supplierSelect: [],
      brandSelect: [],
      categorySelect: [],
      partName: row?.partName ?? null,
      norm: row?.norm ?? null,
      categoryId: null,
      inmark: row?.inmark ?? null,
      brandId: row?.brandId ?? null,
      price: row?.price ?? null,
      supplierId: row?.supplierId ?? null,
      code: row?.code ?? null,
      categoryOption: categoryOption.value
    };

    formInline.categorySelect = resCategory?.result ?? [];
    formInline.categoryId = row?.categoryId ?? null;
    if(resSupplier?.code ===200) {
      formInline.supplierSelect = resSupplier?.result ?? []
    } else {
      message(`供应商获取失败`, {
        type: "warning"
      });
      return
    }


    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              partName: curData.partName,
              norm: curData.norm,
              categoryId: curData.categoryId,
              // inmark: curData.inmark,
              brandId: curData.brandId,
              price: curData.price,
              supplierId: curData.supplierId,
              partId: curData.id,
              code: curData.code,
            }
            if (title === "创建配件") {
              partStoreApi(toRaw(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              partUpdateApi(params).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('请继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      partDeleteApi({ partId: row.partId }).then((res) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    categoryOption
  };
}
